<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\Models\UsrGroup;

class UsrGroupController extends Controller
{
    protected $name = '角色管理';
    protected $field = ['id', 'usrgroupid', 'name', 'orderid', 'synstate', 'des', 'state'];
    protected $find = ['id', 'usrgroupid', 'name', 'orderid', 'synstate', 'modifier', 'tabnm', 'updated_at', 'created_at', 'des', 'state'];
    protected $datefield = [];

    /**
     * 查询
     */
    public function find(Request $request)
    {
        $param = json_decode($request->param, true);
        $name = $this->I($param['name'] ?? null);
        $usrgroupid = $this->I($param['usrgroupid'] ?? null);
        $des = $this->I($param['des'] ?? null);
        $tabnm = $this->I($param['tabnm'] ?? null);
        $state = $this->I($param['state'] ?? null);
        $keyvalue = $this->I($param['keyvalue'] ?? null);
        $page = intval($this->I($param['page'] ?? 1));
        $pagecount = intval($this->I($param['pagecount'] ?? 10));
        $where = ' a.isdel=0 ';
        if (!empty($name)) {
            $where .= " and a.name = '$name' ";
        }
        if (!empty($usrgroupid)) {
            $where .= " and a.usrgroupid = '$usrgroupid' ";
        }
        if (!empty($des)) {
            $where .= " and a.des = '$des' ";
        }
        if (!empty($tabnm)) {
            $where .= " and a.tabnm = '$tabnm' ";
        }
        if (!empty($state)) {
            $where .= " and a.state = '$state' ";
        }
        if (!empty($keyvalue)) {
            $where .= " and (a.name = '$keyvalue' or a.usrgroupid = '$keyvalue') ";
        }
        $temp = DB::table('UsrGroup as a')
            ->select($this->find)
            ->whereRaw($where)
            ->paginate($pagecount, ['id'], 'page', $page)
            ->toArray(); // 控制页码，默认每页 10 条
        $res = $temp['data'];
        $allcount = $temp['total'];
        //记录日志
        //$this->log(['operator' => null, 'type' => '查看', 'billcaption' => '角色管理', 'des' => '操作人[查看]了角色管理,查询条件为[' .json_encode($param) . ']']);
        return $this->ajaxReturn(['code' => 1, 'msg' => $this->name . '|查询成功!', 'count' => $allcount, 'data' => $res]);
    }

    /**
     * 保存
     */
    public function save(Request $request)
    {
        $usr = $this->decodetoken();
        $param = json_decode($request->param, true);
        $id = $this->I($param['id'] ?? null);
        $isnew = false;
        if (empty($id)) {
            $isnew = true;
        }
        $list = [];
        if (empty($param)) {
            return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '|保存参数为空']);
        }
        foreach ($param as $key => $value) {
            if (in_array($key, $this->field)) {
                $list[$key] = $value;
            }
        }
        if (empty($list)) {
            return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '|没有需要处理的数据']);
        }
        //新增
        $type = '';
        if ($isnew) {
            $type = '新增';
            if (empty($list['usrgroupid'])) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '新增失败!角色ID不能为空']);
            }
            if (empty($list['name'])) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '新增失败!角色名称不能为空']);
            }
            $FSQL = "  select * from UsrGroup where isdel=0 and (usrgroupid='" . $list['usrgroupid'] . "' or name='" . $list['name'] . "')";
            if (!empty(DB::select($FSQL))) {
                return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '|角色ID或姓名已经存在,不可重复']);
            }
            $list['tabnm'] = $usr->name;
            //新增
            $res = UsrGroup::create($list);
            if (empty($res)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '|新增失败!']);
            }
        } else {
            $type = '修改';
            $list['synstate'] = 0;
            $list['modifier'] = $usr->name;
            //修改   
            $uptab = UsrGroup::find($id);
            if ($uptab->name == '系统管理员') {
                return $this->ajaxReturn(['code' => 0, 'msg' => '系统管理员信息不能做任何变更']);
            }
            $uptab->update($list);
            $res = $uptab;
        }
        //记录日志
        $this->log(['operator' => $usr->name, 'type' => $type, 'billcaption' => '角色管理', 'des' => '操作人[' . $type . ']了角色|[' . $res->name . '],|数据为|[' . json_encode($list) . ']']);
        return $this->ajaxReturn(['code' => 1, 'msg' => $this->name . '保存成功!']);
    }

    /**
     * 删除
     */
    public function delete(Request $request)
    {
        try {
            $param = json_decode($request->param, true);
            $id = $this->I($param['id'] ?? null);
            if (empty($id)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '删除失败!角色ID为空']);
            }
            $FSQL = "SELECT a.id,a.name,a.usrgroupid
              FROM UsrGroup a where id in($id)";
            $data = DB::select($FSQL);
            if (empty($data)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '删除失败!角色不存在']);
            } 
            if ($data[0]->usrgroupid == '000') {
                return $this->ajaxReturn(['code' => 0, 'msg' => '删除失败!系统管理员不能删除']);
            }
            $EXESQL = "UPDATE UsrGroup SET isdel=1 WHERE id in($id)";
            $res = DB::update($EXESQL);
            if (empty($res)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '删除失败!']);
            }
            $FSQL = "SELECT id,usrgroupid,name,des,tabnm,created_at,modifier,updated_at 
            FROM UsrGroup  where isdel=0";
            $data = DB::select($FSQL);
            //记录日志
            $this->log(['type' => '删除', 'billcaption' => '角色管理', 'des' => '操作人[删除]了角色|[' . $data[0]->name . '],I|D为|[' . $data[0]->usrgroupid . ']']);
            return $this->ajaxReturn(['code' => 1, 'msg' => '删除成功!', 'data' => $data]);
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '导入失败：' . $e->getMessage()]);
        }
    }

    /**
     * excel导入
     */
    public function excelimport(Request $request)
    {
        try {
            $usr = $this->decodetoken();
            $param = json_decode($request->param, true);
            if (empty($param)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '导入失败!数据为空']);
            }
            $i = 2;
            //获取所有数据
            $FSQL = "select usrgroupid,name from UsrGroup where isdel=0";
            $ALLdata = DB::select($FSQL);
            $idkey = [];
            $namekeyreapt = [];
            foreach ($ALLdata as $key) {
                $idkey[$key->usrgroupid] = 1;
                $namekeyreapt[$key->name] = $key->usrgroupid;
            }
            $indata = [];
            $updata = [];
            $keynm = [];
            $keyid = [];
            $iscover = $param['iscover'];
            $data = $param['data'];
            foreach ($data as $key) {
                $id = trim($key['usrgroupid'] ?? null);
                $name = trim($key['name'] ?? null);
                if (empty($id)) {
                    return $this->ajaxReturn(['code' => 0, 'msg' => '导入失败!第|' . $i . '|行角色ID不能为空']);
                }
                if (empty($name)) {
                    return $this->ajaxReturn(['code' => 0, 'msg' => '导入失败!第|' . $i . '|行角色名称不能为空']);
                }
                if (in_array($name, $keynm)) {
                    return $this->ajaxReturn(['code' => 0, 'msg' => '导入失败!第|' . $i . '|行角色名称出现重复']);
                }
                if (in_array($id, $keyid)) {
                    return $this->ajaxReturn(['code' => 0, 'msg' => '导入失败!第|' . $i . '|行角色ID出现重复']);
                }
                if (($namekeyreapt[$name] ?? null) != null && ($namekeyreapt[$name] ?? null) != $id) {
                    return $this->ajaxReturn(['code' => 0, 'msg' => '导入失败!第|' . $i . '|行角色名称已经被使用']);
                }
                if ($name == '系统管理员') {
                    return $this->ajaxReturn(['code' => 0, 'msg' => '导入失败!第|' . $i . '|行角色为系统管理员']);
                }
                $keynm[] = $name;
                $keyid[] = $id;
                $obj = [];
                //组装需要处理的字段
                foreach ($key as $field => $value) {
                    //字段是否存在校验
                    if (in_array($field, $this->field)) {
                        //日期校验
                        if (in_array($field, $this->datefield) && strtotime($value) == false) {
                            $obj[$field] = null;
                        } else {
                            $obj[$field] = $value;
                        }
                    }
                }
                if (($idkey[$id] ?? null) == 1) {
                    //修改
                    $obj['modifier'] = $usr->name;
                    $updata[] = $obj;
                } else {
                    $obj['created_at'] = date('Y-m-d H:i:s');
                    $obj['tabnm'] = $usr->name;
                    //新增
                    $indata[] = $obj;
                }
                $i++;
            }
            if (!empty($indata)) {
                $res = DB::table('UsrGroup')->insert($indata);
                if (empty($res)) {
                    return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '|导入失败!']);
                }
            }
            //记录日志
            $this->log(['operator' => $usr->name, 'type' => 'excel导入', 'billcaption' => '角色管理', 'des' => '操作人进行了excel导入,数据为|[' . json_encode($data) . ']']);
            return $this->ajaxReturn(['code' => 1, 'msg' => '导入成功！', 'indata' => $indata, 'updata' => $idkey]);
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '导入失败：' . $e->getMessage()]);
        }
    }
}
